package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

// GetAll 获取当前所有社团和活动信息并在首页轮播显示
func GetAll(ctx *gin.Context) {
	//获取十佳社团数据
	DB := common.GetDB()

	// 获取当前年份,查询符合条件的 Cid 列表
	currentYear := time.Now().Year()
	var outstandingClubs []model.OutstandingClubs
	DB.Where("YEAR(Otime) = ?", currentYear).Find(&outstandingClubs)

	// 获取这些 Cid 对应的社团信息
	var tenclubs []model.Club
	var cids []int
	for _, oc := range outstandingClubs {
		cids = append(cids, oc.Cid)
	}

	result := DB.Where("id IN (?)", cids).Find(&tenclubs)
	if result.Error != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:")
		return
	}
	print(result.Count)

	var tenimages []model.CImage
	err5 := DB.Where("Cid IN (?) AND Main=?", cids, 1).Find(&tenimages).Error
	if err5 != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err5)
		return
	}

	//获取所有社团信息
	DB1 := common.GetDB()
	DB1 = DB1.Where("Exist=?", 1)
	var clubs []model.Club
	err1 := DB1.Find(&clubs).Error
	if err1 != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err1)
		return
	}

	// 获取社团图片
	DB2 := common.GetDB()
	var images []string
	for _, club := range clubs {
		var tmp []model.CImage
		err2 := DB2.Where("Cid=? AND Main=?", club.Cid, 1).Find(&tmp).Error
		if err2 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err1:", err2)
			return
		}
		for _, image := range tmp {
			images = append(images, image.Path) // 只添加路径字段
		}
	}

	//获取所有活动信息
	DB3 := common.GetDB()
	DB3.Where("State IN (?)", []int{1, 2, 3})

	var activities []model.Activity
	err3 := DB3.Find(&activities).Error
	if err3 != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err3)
		return
	}

	//获取公告信息
	Db := common.GetDB()
	var notices []model.Notice

	// 查询并按照 CreatedAt 时间倒序排序
	err4 := Db.Order("Ntime DESC").Find(&notices).Error
	if err4 != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("err:", err4)
		return
	}

	// 返回查询结果
	response.Success(ctx, gin.H{"tenclubs": tenclubs, "tenimages": tenimages, "clubs": clubs, "images": images, "activities": activities, "notices": notices}, "获取成功")
}
